<?php
namespace app\controllers;


use Yii;
use yii\web\MethodNotAllowedHttpException;
use zonday\weixin\api;
use zonday\weixin\message\Text;

class WeixinController extends BaseController
{
    public $enableCsrfValidation = false;

    public function behaviors()
    {
        return [];
    }

    public function actionIndex()
    {
        $request = Yii::$app->getRequest();
        /** @var \zonday\weixin\Weixin $weixin */
        $weixin = Yii::$app->weixin;
        $result = $weixin->receive($request->getRawBody(), $request->getQueryParams());

        if ($result instanceof \zonday\weixin\event\Event) {
            echo $this->processEvent($result);
        } elseif ($result instanceof \zonday\weixin\message\Message) {
            echo $this->processMessage($result);
        } else {
            echo $result;
        }
    }

    /**
     * @return \zonday\weixin\Weixin
     */
    public function getWeixin()
    {
        return Yii::$app->weixin;
    }

    protected function processEvent($event)
    {
        return '';
    }

    /**
     * @param \zonday\weixin\message\Message $message
     * @return string
     */
    protected function processMessage($message)
    {
        if ($message instanceof Text) {
            $text = new Text();
            $text->FromUserName = $message->ToUserName;
            $text->ToUserName = $message->FromUserName;
            $text->CreateTime = time();
            $text->Content = $message->Content;
            (new api\Message())->textMsg($message->FromUserName, 'test')->customSend();
            return $this->getWeixin()->reply($text);
        }
    }
}
